import datetime

from flask import Blueprint, jsonify, g
from flask_restful import Api, Resource, reqparse, abort, marshal, fields


from apps.models.moey_model import WalletMoney

from apps.utils.decorator import login_required
from exts import db
from apps.models.heyue_model import Agreement, AgreementType

heyue_bp = Blueprint('heyue', __name__, url_prefix='/heyue')

api = Api(heyue_bp)

parser = reqparse.RequestParser()

parser.add_argument('title', type=str, required=True, help='必须输入合约标题')
parser.add_argument('content', type=str, required=True, help='必须输入合约内容')
parser.add_argument('type', type=int, required=True, help='必须输入合约类型')
parser.add_argument('end_time', type=str, required=True, help='必须输入结束时间')
parser.add_argument('dizhi', type=str, required=True, help='必须输入充值地址')


agreement_fileds = {
    # 合约标题
    'title': fields.String,
    # 合约内容
    'content': fields.String,
    # 合约类型
    'atype': fields.Integer,
    # 封盘时间
    'end_time': fields.DateTime,
    # 合约创建时间（自动添加）
    'add_time': fields.DateTime,

    'status': fields.Integer
}


class HeyueResource(Resource):
    @login_required
    def post(self):
        user = g.user

        if user:
            args = parser.parse_args()
            h_title = args.get('title')
            h_content = args.get('content')
            h_type = args.get('type')
            h_endtime = args.get('end_time')
            dizhi = args.get('dizhi')
            if h_type in range(1, 6):
                money = WalletMoney.query.filter(WalletMoney.money_localtion == dizhi).first()
                if money:
                    moneyA_count = 20
                    if moneyA_count > money.moneyA:
                        abort(400, msg='现有A币不足')
                    else:
                        money.moneyA -= moneyA_count
                        db.session.add(money)
                        db.session.commit()

                        agreement = Agreement()
                        agreement.title = h_title
                        agreement.content = h_content
                        agreement.atype = h_type
                        agreement.end_time = datetime.datetime.strptime(h_endtime, "%Y-%m-%d %H:%M:%S")
                        agreement.user_id = user.id

                        db.session.add(agreement)
                        db.session.commit()

                        data = {
                            'status': 200,
                            'msg': '合约创建成功',
                            'agreement': marshal(agreement, agreement_fileds)
                        }

                        return jsonify(data)
                else:
                    abort(401, msg='地址输入有误')
            else:
                abort(402, msg='类型输入有误')

api.add_resource(HeyueResource, '/')
